import * as XLSX from 'xlsx'
import { saveAs } from 'file-saver'

// 策略模式 - 导出策略
export class ExportStrategy {
  export(data, filename) {
    throw new Error('抽象方法，需要子类实现')
  }
}

// Excel导出策略
export class ExcelExportStrategy extends ExportStrategy {
  export(data, filename) {
    try {
      const wb = XLSX.utils.book_new()
      
      // 学生维度统计表
      const studentData = data.studentStats.map(student => ({
        '学号': student.studentId,
        '姓名': student.name,
        '缺交数量': student.missingCount,
        '缺交实验列表': student.missingExperiments.join(', ')
      }))
      
      const studentWs = XLSX.utils.json_to_sheet(studentData)
      XLSX.utils.book_append_sheet(wb, studentWs, '学生维度统计')
      
      // 实验维度统计表
      const experimentData = data.experimentStats.map(exp => ({
        '实验名称': exp.experimentName,
        '缺交人数': exp.missingCount,
        '提交率': (exp.submitRate * 100).toFixed(2) + '%',
        '缺交学生列表': exp.missingStudents.map(s => s.name).join(', ')
      }))
      
      const experimentWs = XLSX.utils.json_to_sheet(experimentData)
      XLSX.utils.book_append_sheet(wb, experimentWs, '实验维度统计')
      
      // 导出Excel文件
      const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' })
      const blob = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' })
      saveAs(blob, `${filename}.xlsx`)
      
      return { success: true }
    } catch (error) {
      console.error('Excel导出错误:', error)
      return { success: false, error: error.message }
    }
  }
}

// CSV导出策略
export class CSVExportStrategy extends ExportStrategy {
  export(data, filename) {
    try {
      // 学生维度统计
      let csvContent = '学号,姓名,缺交数量,缺交实验列表\n'
      
      data.studentStats.forEach(student => {
        csvContent += `${student.studentId},${student.name},${student.missingCount},"${student.missingExperiments.join(', ')}"\n`
      })
      
      const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      saveAs(blob, `${filename}-学生统计.csv`)
      
      // 实验维度统计
      csvContent = '实验名称,缺交人数,提交率,缺交学生列表\n'
      
      data.experimentStats.forEach(exp => {
        const submitRate = (exp.submitRate * 100).toFixed(2) + '%'
        const missingStudents = exp.missingStudents.map(s => s.name).join(', ')
        csvContent += `${exp.experimentName},${exp.missingCount},${submitRate},"${missingStudents}"\n`
      })
      
      const blob2 = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
      saveAs(blob2, `${filename}-实验统计.csv`)
      
      return { success: true }
    } catch (error) {
      console.error('CSV导出错误:', error)
      return { success: false, error: error.message }
    }
  }
}

// 导出上下文
export class ExportContext {
  constructor(strategy) {
    this.strategy = strategy
  }
  
  setStrategy(strategy) {
    this.strategy = strategy
  }
  
  executeExport(data, filename) {
    return this.strategy.export(data, filename)
  }
} 